package com.battlebardgames.simplejavacache.key;

import java.lang.reflect.Method;
import java.security.MessageDigest;

/**
 * A cache key provider which generates MD5 keys based on 
 * keys generated from another cache key provider
 * 
 * @author Thomas Cashman
 */
public class MD5KeyProvider implements ICacheKeyProvider {
	private ICacheKeyProvider m_baseProvider;

	/**
	 * Constructor
	 * @param baseProvider Key provider to base MD5 checksums from
	 */
	public MD5KeyProvider(ICacheKeyProvider baseProvider) {
		m_baseProvider = baseProvider;
	}

	@Override
	public String getCacheKey(Object object, Method method, Object[] parameters) {
		return this.getCacheKey(m_baseProvider.getCacheKey(object, method, parameters));
	}

	@Override
	public String getCacheKey(Object object) {
		return this.getCacheKey(m_baseProvider.getCacheKey(object));
	}

	/**
	 * Returns the MD5 cache key for a given string
	 * @param key Key provided by another key provider
	 * @return MD5 checksum
	 */
	private String getCacheKey(String key) {
		String result = key;

		if(key != null && key.length() > 0) {
			try {
				MessageDigest md = MessageDigest.getInstance("MD5");
				md.update(key.getBytes());

				byte byteData[] = md.digest();
				StringBuffer sb = new StringBuffer();
				for (int i = 0; i < byteData.length; i++) {
					sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16)
							.substring(1));
				}

				result = sb.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
}
